package com.cx.base.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.WindowInsets;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.cx.base.R;
import com.cx.util.ViewHelper;


public class TitleBar extends Toolbar {
    String centerText;
    int textColor = 0;
    int textSize = 15;
    private TextView tvCenter;


    public TitleBar(Context context) {
        super(context);
        init(context, null);
    }

    public TitleBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }


    private void init(Context context, @Nullable AttributeSet attrs) {

        LayoutInflater.from(context).inflate(R.layout.base_widget_titlebar, this);
        tvCenter = findViewById(R.id.tv_center);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TitleBar, 0, 0);
        try {
            centerText = typedArray.getString(R.styleable.TitleBar_title_text);
            textColor = typedArray.getColor(R.styleable.TitleBar_textColor, textColor);
            textSize = typedArray.getDimensionPixelOffset(R.styleable.TitleBar_textSize, textSize);
        } finally {
            typedArray.recycle();
        }
        setTitle("");
        setCenterText(centerText);
        setCenterTextColor(textColor);
        tvCenter.getPaint().setTextSize(textSize);
    }


    @Override
    public WindowInsets onApplyWindowInsets(final WindowInsets insets) {
        if (getFitsSystemWindows()) {
            post(new Runnable() {
                @Override
                public void run() {
                    ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) getLayoutParams();
                    layoutParams.topMargin = insets.getSystemWindowInsetTop();
                    setLayoutParams(layoutParams);
                }
            });
        }
        return insets;
    }


    public void setCenterText(String centerText) {
        this.centerText = centerText;
        ViewHelper.bindToTextView(tvCenter, centerText);
    }


    public void setCenterTextColor(@ColorInt int color) {
        textColor = color;
        tvCenter.setTextColor(textColor);
    }

    public void setCenterTextSize(int size) {
        textSize = size;
        tvCenter.setTextSize(textSize);
    }
}
